import md5 from "md5";
import {loginUser, getProfile, registerUser} from "@/api/sys";
import {message} from '@/libs'
import {LOGIN_TYPE_OAUTH_NO_REGISTER} from '@/constants/index.js'

export default {
  namespaced: true,
  state: () => {
    return {
      token: '',
      userInfo: {}
    }
  },

  mutations: {
    setToken(state, newToken) {
      state.token = newToken;
    },
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo;
    },
  },
  actions: {
    async register(context, payload) {
      const {password} = payload

      return await registerUser({
        ...payload,
        password: password ? md5(password) : ''
      })
    },
    async login(context, payload) {
      const {password} = payload

      const data = await loginUser({
        ...payload,
        password: password ? md5(password) : ''
      }).catch(() => {
        message('error', '用户名或密码错误')
      })

      // 判断是否需要注册
      if(data.code === LOGIN_TYPE_OAUTH_NO_REGISTER) {
        return data.code
      }

      context.commit('setToken', data.token)
      context.dispatch('getProfile')
    },

    async getProfile(context) {
      const data = await getProfile()
      context.commit('setUserInfo', data)
      message('success', `欢迎${data.vipLevel? '尊贵的VIP' + data.vipLevel + '用户' + data.nickname : data.nickname} 登录`)
    },

    logout(context) {
      context.commit('setToken', '')
      context.commit('setUserInfo', {})

      location.reload()
    }
  }
};
